//
//  ViewController.swift
//  LoadWebData
//
//  Created by liy on 2025/1/18.
//

import UIKit

class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()

//    load1()
    sessionLoadGet()
    // 调用函数执行 POST 请求
		sessionPostRequest()
  }

  /// 此种加载数据方式是同步，会影响主线程刷新，一般是适用于测试请求，加载本地文件，不适合加载网络
  func load1() {
    // 字符串形式
    if let url = URL(string: "https://jikexueyuan.com"),
       let str = try? String(contentsOf: url, encoding: .utf8) {
      print(str)
    }

    // 二进制形式
    if let url = URL(string: "https://jikexueyuan.com"),
       let data = try? Data(contentsOf: url) {
      print(data)
    }
  }

  /// 使用NSURLConnection
  /// 同步请求方法:sendSynchronousRequest
  /// 异步：sendAsynchronousRequest
  func load2() {
    if let url = URL(string: "https://jikexueyuan.com") {
      let rq = URLRequest(url: url)
      let resp: URLResponse?
      //			NSURLConnection.senda(r, returning: AutoreleasingUnsafeMutablePointer<URLResponse?>?)
    }
  }

  /// NSURLSession推荐
  func sessionLoadGet() {
    if let url = URL(string: "https://jsznoa.com") {
      let request = URLRequest(url: url)
      let session = URLSession.shared
      let task = session.dataTask(with: request) { data, _, error in
        if let data = data {
          // 处理返回的数据
          print(String(data: data, encoding: .utf8) ?? "")
        } else if let error = error {
          // 处理错误
          print("请求出错: \(error.localizedDescription)")
        }
      }
      task.resume()
    }
  }

  func sessionPostRequest() {
    // 1. 定义请求的 URL
    guard let url = URL(string: "https://example.com/api/endpoint") else {
      print("Invalid URL")
      return
    }

    // 2. 创建 URLRequest 对象并设置 HTTP 方法为 POST
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    // 3. 设置请求的 HTTP 头（可选）
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    // 4. 设置请求的主体内容（可选）
    let parameters: [String: Any] = ["key1": "value1", "key2": "value2"]
    do {
      let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
      request.httpBody = jsonData
    } catch {
      print("Failed to serialize JSON: \(error)")
      return
    }

    // 5. 创建 URLSession 数据任务
    let session = URLSession.shared
    let task = session.dataTask(with: request) { data, response, error in
      if let error = error {
        // 处理错误
        print("Error occurred: \(error)")
        return
      }

      guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
      }

      print("Status code: \(httpResponse.statusCode)")

      if let data = data {
        // 处理返回的数据
        if let responseString = String(data: data, encoding: .utf8) {
          print("Response data: \(responseString)")
        }
      }
    }

    // 6. 启动任务
    task.resume()
  }
}
